import {Component, OnInit, Output, EventEmitter, Input} from '@angular/core';
import {ProductService} from "../../../welcome/business/product/service/product.service";
import {ProductProjectFilter} from "./product-project-filter";
import {BarnProduct} from "../../../welcome/business/product/entity/barn-product";
import {BarnProject} from "../../../welcome/business/project/entity/barn-project";
import {ProjectProductService} from "../../../welcome/business/service/project-product.service";
import {SelectionResult} from "./selection-result";


@Component({
  selector: 'app-product-project-selection',
  templateUrl: './product-project-selection.component.html',
  styleUrls: ['./product-project-selection.component.less']
})
export class ProductProjectSelectionComponent implements OnInit {


  /**
   * excluded project
   */
  @Input()
  filter: ProductProjectFilter
  @Output()
  success = new EventEmitter()
  @Output()
  cancel = new EventEmitter()

  products: BarnProduct[]
  selectedProduct: BarnProduct

  projects: BarnProject[]
  selectedProject: BarnProject

  productLoading = false
  productCurrent = 1;
  productTotal = 100;
  productPageSize = 20

  projectLoading = false;


  constructor(private productService: ProductService, private ppService: ProjectProductService) {
  }

  ngOnInit(): void {
    this.queryProduct()
  }

  queryProduct() {

    this.productLoading = true
    const param = new BarnProduct();
    param.enable = '1'
    this.productService.query(param, this.productCurrent, this.productPageSize).subscribe(value => {
      this.products = value.data
      this.productCurrent = value.current
      this.productTotal = value.count;
      this.productLoading = false;
    }, () => this.productLoading = false)
  }

  selectProduct(product: BarnProduct) {
    if (this.selectedProduct && product.pid === this.selectedProduct.pid) {
      return
    }
    this.selectedProduct = product
    this.queryProject(this.selectedProduct.pid);
  }

  private queryProject(productId: string) {
    this.ppService.getProjectByProduct(productId).subscribe(value => {
      this.projects = value
    })
  }

  selectedSuccess() {
    const result = new SelectionResult();
    result.product = this.selectedProduct;
    result.project = this.selectedProject;
    this.success.emit(result)
  }

  cancelEvent() {
    this.cancel.emit();
  }


}
